<template>
    <div class="zh-authority">
        <el-radio-group v-model="limitType" @change="getLimitType">
			<el-radio :label="1">不限制</el-radio>
            <el-radio :label="2">谁可以看</el-radio>
            <el-radio :label="3">谁不能看</el-radio>
		</el-radio-group>
        <div v-if="limitType === 2 || limitType === 3" class="contentBox">
			<div class="leftBox">
			<h4>选择</h4>
			<template>
                <el-tabs :tab-position="tabPosition" style="height: 90%;border: 1px solid #EBEEF5;">
					<el-tab-pane label="按班级分" style="height: 315px; overflow: auto;">
						<el-tree
						:data="classAuthorityData"
						:props="defaultProps"
						show-checkbox
						@check="getClassAuthority"
						ref="treeAuthority"
						node-key="id"
						default-expand-all
						:expand-on-click-node="false">
						</el-tree>
					</el-tab-pane>
					<el-tab-pane label="按角色分">
						<el-checkbox-group v-model="selectRole" style="height: 315px; overflow: auto;">
							<el-checkbox style="display: block;" v-for="item in allRoleList" :key="item.id" :label="item">{{item.name}}</el-checkbox>
						</el-checkbox-group>
					</el-tab-pane>
					<el-tab-pane label="选择用户">
						<el-input type="text" @keyup.enter.native="seachUser"
							style="margin-bottom: 5px; width:260px;" placeholder="请输入用户名" 
							v-model.trim="userParam.n_n_e" clearable @clear="clearRest">
							<el-button slot="append" icon="el-icon-search" @click="seachUser"></el-button>
						</el-input>
						<el-table
							style="height: 246px;"
							:data="userData"
							@select="selectItem"
							@select-all="selectAll"
							@selection-change="handleSelectionChange"
							ref="multipleTable">
							<el-table-column type="selection"></el-table-column>
							<el-table-column prop="name" label="用户名" align="center"	show-overflow-tooltip></el-table-column>
							<el-table-column prop="number" label="账号"	align="center" show-overflow-tooltip></el-table-column>
						</el-table>
						<el-pagination
							small
							@size-change="handleSizeChange"
							@current-change="handleCurrentChange"
							layout="prev, pager, next"
							:current-page="userParam.page"
							:total="total_number">
						</el-pagination>
					</el-tab-pane>
				</el-tabs>
			</template>
			</div>
			<div class="rightBox">
			    <h4>已选</h4>
                <ul class="tagBox">
                    <li>
                        <el-tag
                            v-for="tag in classNameData"
                            :key="JSON.stringify(tag)"
                            closable
                            @close="closeTag(tag, 'class')"
                            type="info">
                            {{tag.rename}}
                        </el-tag>
                    </li>
                    <li>
                        <el-tag
                            v-for="tag in selectRole"
                            :key="JSON.stringify(tag)"
                            closable
                            @close="closeTag(tag, 'role')"
                            type="info">
                            {{tag.name}}
                        </el-tag>
                    </li>
                    <li>
                        <el-tag
                            v-for="tag in selectList"
                            :key="JSON.stringify(tag)"
                            closable
                            @close="closeTag(tag, 'user')"
                            type="info">
                            {{tag.name}}
                        </el-tag>
                    </li>
                </ul>
			</div>
		</div>
    </div>
</template>
<script>
    export default {
        props: {
            editData: {
                type: Object,
                default: {1: [],2: [],3: [],4: 1,}
            }
        },
        data() {
            return {
                limitType: 1,
                tabPosition: '按班级分',
                classAuthorityData: [], // 班级数据
				allRoleList: [], // 角色数据
                selectRole: [], // 选中的角色
                defaultProps: {
					children: 'children',
					label: 'name',
					disabled:'disabled'
                },
                authorityNodeste: [], // 被选中的班级
				selectList: [], //选中的用户
				userData: [], // 用户数据
                total_number: 0,
				userParam: {
					page: 1,
					size: 5,
					n_n_e: '',
					data_type: 2,
					order: 'alphabetically',
					not_role_id: '2,3',
                },
				classNameData: [], // 班级名称数据
                emitData: {
                    classNameData: [],
                    selectRole: [],
                    selectList: [],
                    limitType: 1,
                },
            }
        },
        created() {
            this.allRole();
            this.getClassData();
            this.getUserData();
        },
        watch: {
            classNameData: {
                handler(newVal, oldVal){
                    if(newVal) {
                        this.emitData.classNameData = this.classNameData
                        this.$emit('resChosed', this.emitData)
                    }
                },
                deep: true,
            },
            selectRole: {
                handler(newVal, oldVal){
                    if(newVal) {
                        this.emitData.selectRole = this.selectRole
                        this.$emit('resChosed', this.emitData)
                    }
                },
                deep: true,
            },
            selectList: {
                handler(newVal, oldVal){
                    if(newVal) {
                        this.emitData.selectList = this.selectList,
                        this.$emit('resChosed', this.emitData)
                    }
                },
                deep: true,
            },
            'limitType'(newVal, oldVal) {
                if(newVal) {
                    this.emitData.limitType = this.limitType,
                    this.$emit('resChosed', this.emitData)
                }
            }
        },
        methods: {
            changeAuthorityValue() {
                if(this.editData['4'] === 1) return
                this.limitType = this.editData['4']
                this.classNameData = this.editData['1']
                this.selectRole = this.editData['2']
                this.selectList = this.editData['3']
            },
            
            getLimitType() {
                for (var i of this.classNameData) {
                    this.$refs.treeAuthority.setChecked(i.id, false);
                }
                this.$refs.multipleTable && this.$refs.multipleTable.clearSelection()
                this.classNameData = []
                this.selectRole = []
                this.selectList = []
            },
            getClassAuthority() { // 被选中班级
				this.authorityNodeste = this.$refs.treeAuthority.getCheckedNodes();
                this.classNameData = this.authorityNodeste.filter(i => i.rename)
            },
            getClassData() { /** 获取组织架构 */
				let success = res => {
                    this.classAuthorityData = res.data[0].children // 权限班级数据
                    this.setSelect('class')
				}
				this.$ajax.get('api/org/org', {params: {for_company: 1, status: [1, 2], data_type: "manage_tree"},func: {success}})
            },
            allRole() { // 获取所有角色
				let success = (res => {
                    this.allRoleList = res.data;
                    this.setSelect('role')
				});
				this.$ajax.get('api/role/get_all_role', {params: {type: 1},func: {success}})
            },
            getUserData() {
				let success = res => {
					this.total_number = res.data.data_sum*2;
					this.userData = res.data.data
					this.setSelect('user')
				}
				this.$ajax.get('api/user/user', {params: this.userParam,func: {success}})
            },
            clearRest() {
				this.userParam.n_n_e = ''
				this.userParam.page = 1
				this.getUserData()
			},
			seachUser() {
				this.userParam.page = 1
				this.getUserData()
			},
            handleSizeChange(val) {
				this.userParam.page = 1;
				this.userParam.size = val;
				this.getUserData();
			},
			handleCurrentChange(val) {
				this.userParam.page = val;
				this.getUserData();
			},
            selectItem(selection, row){
				//单选的筛选，将没有的数据添加，有的数据删除。
				let flag = this.selectList.every(item => item.id != row.id); 
				if(!flag){
					let unselect =this.selectList.findIndex((item,index) => {
						if(item.id == row.id){
							return index
						}
					})
					this.selectList.splice(unselect,1)
				}
			},
			selectAll(selection){
				//将原本全选，然后又取消的数据删除
				if(selection.length==0){
					for(let i = 0;i<this.userData.length;i++){
						let index 
						index = this.isSelectedGoods(this.userData[i], this.selectList)
						if (index > -1) {
							this.selectList.splice(index, 1);
						} else {
							this.selectList.push(this.userData[i]);
						}
					}
				}
            },
            handleSelectionChange(val){
				if(val.length>0){
					val.forEach(item=> this.selectList.push(item))
					//对象数组去重
					this.selectList = this.selectList.filter((x, index,self)=>{
						let arrids = []
						let arrnames = []
						this.selectList.forEach((item,i) => {
							arrids.push(item.id)
							arrnames.push(item.name)
						})
						let judgeOne = arrids.indexOf(x.id) === index
						let judgeTwo = arrnames.indexOf(x.name) === index
						return judgeOne || judgeTwo
					})
				}
			},
			setSelect(even){
				//设置选中状态
				this.$nextTick(() => {
                    switch(even) {
                        case 'user':
                            if(this.selectList.length && this.selectList.length>0){
                                this.userData.forEach(row => {
                                    this.selectList.forEach(p => {
                                        if (row.id === p.id) {
                                            this.$refs.multipleTable.toggleRowSelection(row);
                                        }
                                    });
                                });
                            }
                            break;
                        case 'role':
                            let s = [];
                            for (var j of this.selectRole) {
                                for (var m of this.allRoleList) {
                                    if (j.id === m.id) {
                                        s.push(m);
                                    }
                                }
                            }
                            this.selectRole = s;
                            break;
                        case 'class':
                            for (var i of this.classNameData) {
                                this.$refs.treeAuthority.setChecked(i.id, true);
                            }
                            break;
                        default:
                            break;
                    }
				});
			},
			isSelectedGoods(row, list) {
				let rows = JSON.parse(JSON.stringify(row))
				//是否选取 -1表示没选中
				return list.findIndex(item => {
					return item.id == rows.id;
				});
            },
            closeTag(val, even) {
                switch(even) {
                    case 'class':
                        this.classNameData = this.classNameData.filter(i => i.id !== val.id) // 去右
                        this.$refs.treeAuthority.setChecked(val.id,false) // 去左
                        break;
                    case 'role':
                        this.selectRole = this.selectRole.filter(item => item.id !== val.id)
                        break;
                    case 'user':
                        this.selectList = this.selectList.filter(item => item.id !== val.id)
                        this.userData.forEach(row => {
                            if (row.id === val.id) {
                                this.$refs.multipleTable.toggleRowSelection(row);
                            }
                        })
                        break;
                }
            },
        }
    }
</script>
<style lang="scss">
    .zh-authority {
        .contentBox {
            height: 400px;
            width: 100%;
            display: flex;
            padding: 10px 0;
            .leftBox {
                height: 100%;
                width: 48.5%;
                margin-right: 1.5%;
                h4 {
                    margin: 15px 0 5px 0;
                }
                .el-tab-pane {
                    padding-left: 10px;
                }
                .el-tabs__header{
                    margin: 0 0 10px 0;
                }
                .el-tabs__item.is-active{
                    background: none;
                    color: #409EFF;
                }
                .el-tabs__nav-wrap{
                    width: 100%;
                }
                .el-tree-node__content>.el-checkbox {
                    margin-right: 8px;
                }
                .el-tree-node__children {
                    padding-left: 18px !important;
                }
            }
            .rightBox {
                height: 100%;
                width: 49%;
                h4 {
                    padding-left: 20px;
                    margin: 15px 0 5px 0;
                }
                .tagBox {
                    height: 90%;
                    overflow: auto;
                    border: 1px solid #EBEEF5;
                    .el-tag {
                        margin: 5px 0 0 5px;
                    }
                }
            }
        }
    }
</style>